#include "stm32f10x.h"                  // Device header

#include "GPIO.h"

void MySPI_W_CS(uint8_t BitValue)
{
	GPIO_WriteBit(SPI_GPIO, SPI_CS, (BitAction)BitValue);
}

void MySPI_W_SCK(uint8_t BitValue)
{
	GPIO_WriteBit(SPI_GPIO, SPI_SCK, (BitAction)BitValue);
}

uint8_t MySPI_R_MISO(void)
{
	return GPIO_ReadInputDataBit(SPI_GPIO, SPI_MISO);
}

void MySPI_W_MOSI(uint8_t BitValue)
{
	GPIO_WriteBit(SPI_GPIO, SPI_MOSI, (BitAction)BitValue);
}

void MySPI_Init(void)
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
	
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_InitStructure.GPIO_Pin = SPI_MOSI | SPI_CS | SPI_SCK;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(SPI_GPIO, &GPIO_InitStructure);
	
//	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
//	GPIO_InitStructure.GPIO_Pin = SPI_MOSI;
//	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
//	GPIO_Init(SPI_GPIO, &GPIO_InitStructure);
	
	MySPI_W_CS(1);
	MySPI_W_SCK(0);
}

void MySPI_Start(void)
{
	MySPI_W_CS(0);
}

void MySPI_Stop(void)
{
	MySPI_W_CS(1);
}

uint8_t MySPI_SwapByte(uint8_t ByteSend)
{
	uint8_t i, ByteReceive = 0x00;
	
	for (i = 0; i < 8; i ++)
	{
//		MySPI_W_MOSI(ByteSend & (0x80 >> i));
		GPIO_WriteBit(SPI_GPIO, SPI_MOSI, (BitAction)(ByteSend & (0x80 >> i)));
		GPIO_WriteBit(SPI_GPIO, SPI_SCK, (BitAction)1);
//		if (MySPI_R_MISO() == 1){ByteReceive |= (0x80 >> i);}
		GPIO_WriteBit(SPI_GPIO, SPI_SCK, (BitAction)0);
	}
	
	return ByteReceive;
}
